﻿Imports System
Imports System.IO
Imports System.IO.Ports
Imports System.Linq
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Data.SqlServerCe
Imports System.Text
Imports System.Runtime.InteropServices
Imports Microsoft.WindowsMobile.Samples.Location
Imports EFITransmissao

Public Class EFI

    Dim conn As New Conexoes.conexaoSQLServerCE
    Dim efiBs As New EfiBase.GpsCoordenadas
    Dim efiMt As New EfiBase.Metodos

    Private updateDataHandler As EventHandler
    Private device As GpsDeviceState = Nothing
    Private position As GpsPosition = Nothing
    Dim efiGPS As New Gps
    Dim statusGPS As String = Nothing

    Dim listGPS As New ListBox

    Dim arquivo As String = "\Leituras.txt" 'nome do arquivo
    Dim arqControle As String = "\Controle.txt" 'nome do arquivo de controle
    Dim arqGPS As String = "\GPS.txt"

    Dim utm As EfiBase.UTM
    Dim utmX As String = Nothing
    Dim utmY As String = Nothing
    Dim LatG As String = Nothing
    Dim LngG As String = Nothing
    Dim LatD As String = Nothing
    Dim LngD As String = Nothing

    Public Latitude As String
    Public Longitude As String

    Dim newLatitude As Object
    Dim newLongitude As Object

    Private lsf As New List(Of Integer)
    Private lsp As New List(Of String)

    Dim plist As Integer = 1
    Dim pteclado As Integer = 0

    Dim ListPortas As New List(Of String)
    Dim ConfigPorta As Boolean = False
    Dim tamCfPorta As Integer = 4

    Dim PesqAtiva As Boolean = False
    Dim tamCtlPesq As Integer = 12
    Dim IdPesq As Integer = 0

    Dim numReg As Integer = 0
    Dim fts As Integer = 0

    Dim dtLeit As String = Nothing
    Dim hrLeit As String = Nothing

    Dim abertura As Boolean = False
    Dim coletaAtiva As Boolean = False

    Dim strDv As String = Nothing  'Nome do Device GPS
    Dim strLt As String = Nothing 'Latitude do GPS
    Dim strLn As String = Nothing 'Longitude do GPS
    Dim strDgLat As UInteger = Nothing 'Latitude Degrees
    Dim strDgLng As UInteger = Nothing 'Longitude Degrees
    Dim dtGPS As Date = Now 'Data do GPS
    Dim GpsBase As Boolean = True 'Verifica se o GPS está transmitindo as Coordenadas corretas
    Dim pLat As Integer = 0
    Dim pLng As Integer = 0
    Dim latF As Integer = 0
    Dim lngF As Integer = 0
    Dim prmCamera As String = Nothing

    Private Sub CriarArqGPS()

        If Not File.Exists(arqGPS) = True Then

            Dim owGPS As StreamWriter
            owGPS = File.CreateText(arqGPS)

        End If

    End Sub

    Private Function LerArquivoTexto() As Boolean
        'Ler arquivo texto e gravar no banco de dados
        Dim textoSR As StreamReader  'Apenas Leitura
        Dim sLine As String 'linha
        Dim sql As String
        Dim nLinhas As Integer = 1
        Dim IdRotaC As Integer = 0
        Dim IdRotaL As Integer = 0

        Try

            If Not File.Exists(arquivo) Or Not File.Exists(arqControle) Then

                MsgBox("Arquivos não localizados.", MsgBoxStyle.Exclamation, "Coleta de Leituras")

                Return False

            Else

                conn.AbreConexao()

                sql = "Delete From Leituras"
                conn.ExecutaComandoSQL(sql)

                sql = "Delete From Controle"
                conn.ExecutaComandoSQL(sql)

                'Tabela de Controle
                textoSR = New StreamReader(arqControle, Encoding.Default)
                sLine = textoSR.ReadLine

                'IdRota do arquivo de Controle
                IdRotaC = CInt(sLine.Substring(72, 4))

                While Not sLine Is Nothing
                    sql = InsereRegistroControle(sLine)
                    conn.ExecutaComandoSQL(sql)
                    sLine = textoSR.ReadLine
                End While

                textoSR.Close() 'fecha a leitura do arquivo de controle


                'Tabela LeitOrdem
                textoSR = New StreamReader(arquivo, Encoding.Default)
                sLine = textoSR.ReadLine

                'IdRota do arquivo de Leitura
                IdRotaL = CInt(sLine.Substring(282, 4))

                'Comparação do IdRota dos arquivos de Controle e Leitura
                If IdRotaC <> IdRotaL Then

                    MsgBox("Inconsistência no arquivo de Controle.", _
                           MsgBoxStyle.Critical, "Coleta de Leituras")

                    Return False

                End If

                'Tabela de Leitura
                While Not sLine Is Nothing
                    sql = InsereRegistro(sLine, nLinhas)
                    conn.ExecutaComandoSQL(sql)
                    nLinhas = nLinhas + 1
                    sLine = textoSR.ReadLine
                End While

                numReg = nLinhas

                sLine = Nothing
                sql = Nothing
                nLinhas = Nothing

                conn.FechaConexao()

                textoSR.Close()
                textoSR.Dispose()

                Return True

            End If

        Catch ex As Exception

            Return False

        End Try

    End Function

    Private Function OrdenarRoteiro(ByVal nReg As Integer) As Boolean
        'Criar uma nova tabela Ordenada
        Dim iteracao As Integer
        Dim ref As String = Nothing
        Dim ini As Integer = 0
        Dim fim As Integer = 0
        Dim x As Integer = 0
        Dim y As Integer = 1
        Dim bReg As Integer = 50
        Dim dr As DataRow = Nothing
        Dim reg As Integer = Nothing

        iteracao = Fix(nReg / bReg)

        If nReg Mod bReg <> 0 Then
            iteracao = iteracao + 1
        End If

        For y = 1 To iteracao

            Select Case y
                Case Is = 1
                    ini = 1
                Case Else
                    ini = fim + 1
            End Select

            If y = iteracao Then
                fim = nReg
            Else
                fim = ini + (bReg - 1)
            End If


            Try

                conn.AbreConexao()

                Dim sql As String = Nothing

                sql = "select Uc From Leituras Order By SeqLeitura, Endereco, Uc"

                Dim ds As New DataSet()
                Dim adapter As SqlCeDataAdapter

                adapter = conn.PreencheDataSet(ds, sql)

                'Lendo os registros
                reg = 0
                For Each dr In ds.Tables(0).Rows

                    reg = reg + 1

                    If reg >= ini And reg <= fim Then

                        ref = dr.Item("Uc").ToString()

                        sql = "Update Leituras Set IdLeit = " & reg & " Where Uc = '" & ref & "'"

                        conn.ExecutaComandoSQL(sql)

                    End If

                    If reg = fim Then

                        Exit For

                    End If


                Next dr

                reg = Nothing
                sql = Nothing
                dr = Nothing

                ds.Dispose()
                adapter.Dispose()

                conn.FechaConexao()

            Catch ex As Exception

                Return False

            End Try

        Next

        Return True

    End Function

    Private Function InsereRegistroControle(ByVal txt As String) As String

        Dim comando As String

        comando = "Insert Into Controle " & _
                        "(IdLeitura, IdPesquisa, RoteiroRecebido, LeiturasEnviadas, DtLeitInicio, DtLeitFim, " & _
                         "MesFat, Remessa, Matricula, Leiturista, Roteiro, TotRegistros, IdPorta) " & _
                  "Values (1,1,0,0,'" & txt.Substring(0, 10) & "','" & txt.Substring(11, 10) & "'," & _
                           "'" & txt.Substring(22, 10) & "'," & txt.Substring(33, 2) & "," & _
                           "'" & txt.Substring(36, 4) & "','" & txt.Substring(41, 30).Trim & "'," & _
                           "" & txt.Substring(72, 4) & "," & txt.Substring(77, 4) & ",'" & txt.Substring(82, 4) & "')"

        Return comando

    End Function

    Private Function InsereRegistro(ByVal txt As String, ByVal linha As Integer) As String

        Dim comando As String

        comando = "Insert Into Leituras " & _
                        "(IdLeit, SeqLeitura, Endereco, Fase, Medidor, Constante, " & _
                         "LeituraAnterior, LeituraAtual, Classe, LeitMin, LeitMax, " & _
                         "Ocorrencia1, Ocorrencia2, Ocorrencia3, Ocorrencia4, DataLeitura, HoraLeitura, " & _
                         "Uc, Nome, IdRegiao, Ligado, IdMotivoDeslig, OcorrenciaAnt, " & _
                         "IdRota, AcertosLeit, MedidorRetirado, Complemento, Latitude, Longitude, " & _
                         "LatDegress, LngDegress, UTM_x, UTM_y, MedidorAlt, Fabricante, Marca, Modelo, DtHrSat, IdFoto) " & _
                  "Values (" & linha & "," & _
                           "'" & txt.Substring(0, 6) & "','" & txt.Substring(7, 55).Trim.Replace("'", "´") & "'," & _
                           "'" & txt.Substring(63, 1) & "','" & txt.Substring(65, 12) & "'," & _
                           "'" & txt.Substring(78, 2) & "','" & txt.Substring(81, 8) & "'," & _
                           IIf(txt.Substring(90, 8).Trim = "", "Null", "'" & txt.Substring(90, 8).Trim & "'") & "," & _
                           "'" & txt.Substring(99, 1) & "','" & txt.Substring(101, 6) & "'," & _
                           "'" & txt.Substring(108, 6) & "'," & _
                           IIf(txt.Substring(115, 3).Trim = "", "Null", "'" & txt.Substring(115, 3).Trim & "'") & "," & _
                           IIf(txt.Substring(119, 3).Trim = "", "Null", "'" & txt.Substring(119, 3).Trim & "'") & "," & _
                           IIf(txt.Substring(123, 3).Trim = "", "Null", "'" & txt.Substring(123, 3).Trim & "'") & "," & _
                           IIf(txt.Substring(127, 3).Trim = "", "Null", "'" & txt.Substring(127, 3).Trim & "'") & "," & _
                           IIf(txt.Substring(131, 8).Trim = "", "Null", "'" & txt.Substring(131, 8).Trim & "'") & "," & _
                           IIf(txt.Substring(140, 5).Trim = "", "Null", "'" & txt.Substring(140, 5).Trim & "'") & "," & _
                           "'" & txt.Substring(146, 6) & "','" & txt.Substring(170, 100).Trim.Replace("'", "´") & "'," & _
                           "'" & txt.Substring(271, 2) & "','" & txt.Substring(274, 1) & "'," & _
                           "'" & txt.Substring(276, 2) & "','" & txt.Substring(279, 2) & "'," & _
                           "'" & txt.Substring(282, 4) & "'," & _
                           IIf(txt.Substring(287, 4).Trim = "", 0, "'" & txt.Substring(287, 4).Trim & "'") & "," & _
                           IIf(txt.Substring(292, 12).Trim = "", "Null", "'" & txt.Substring(292, 12).Trim & "'") & "," & _
                           IIf(txt.Substring(305, 45).Trim = "", "Null", "'" & txt.Substring(305, 45).Trim.Replace("'", "´") & "'") & "," & _
                           IIf(txt.Substring(351, 15).Trim = "", "Null", "'" & txt.Substring(351, 15).Trim & "'") & "," & _
                           IIf(txt.Substring(367, 15).Trim = "", "Null", "'" & txt.Substring(367, 15).Trim & "'") & "," & _
                           IIf(txt.Substring(383, 15).Trim = "", "Null", "'" & txt.Substring(383, 15).Trim & "'") & "," & _
                           IIf(txt.Substring(399, 15).Trim = "", "Null", "'" & txt.Substring(399, 15).Trim & "'") & "," & _
                           IIf(txt.Substring(415, 15).Trim = "", "Null", "'" & txt.Substring(415, 15).Trim & "'") & "," & _
                           IIf(txt.Substring(431, 15).Trim = "", "Null", "'" & txt.Substring(431, 15).Trim & "'") & "," & _
                           IIf(txt.Substring(447, 12).Trim = "", "Null", "'" & txt.Substring(447, 12).Trim & "'") & "," & _
                           IIf(txt.Substring(460, 20).Trim = "", "Null", "'" & txt.Substring(460, 20).Trim.Replace("'", "´") & "'") & "," & _
                           IIf(txt.Substring(481, 20).Trim = "", "Null", "'" & txt.Substring(481, 20).Trim.Replace("'", "´") & "'") & "," & _
                           IIf(txt.Substring(502, 20).Trim = "", "Null", "'" & txt.Substring(502, 20).Trim.Replace("'", "´") & "'") & "," & _
                           IIf(txt.Substring(523, 19).Trim = "", "Null", "'" & txt.Substring(523, 19).Trim & "'") & "," & _
                           IIf(txt.Substring(543, 12).Trim = "", "Null", "'" & txt.Substring(543, 12).Trim & "'") & ")"

        Return comando

    End Function

    Private Sub bGravar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bGravar.Click
        Dim comando As String = Nothing
        Dim dr As SqlCeDataReader = Nothing
        Dim acertos As Integer = 0
        Dim sql As String = Nothing
        Dim chCamera As Boolean = False

        lbl_Contador.Visible = False

        prmCamera = ""
        utmX = efiBs.DefaultUtmX.ToString()
        utmY = efiBs.DefaultUtmY.ToString()

        Try

            GeraCoordenadas()

            utmX = efiMt.ValorDecimalTruncar(3, Convert.ToDouble(utm.Easting.ToString()))
            utmY = efiMt.ValorDecimalTruncar(3, Convert.ToDouble(utm.Northing.ToString()))

        Catch ex As Exception

            If dtLeit = "" Or dtLeit = Nothing Then

                dtLeit = Format(Date.Now, "dd/MM/yy")
                hrLeit = Format(Date.Now, "HH:mm")

            End If

            dtGPS = Format(Convert.ToDateTime(Date.Now), "dd/MM/yyyy HH:mm:ss")

            LatG = efiBs.DefaultLat
            LngG = efiBs.DefaultLong

            LatD = efiBs.DefaultLatitude.ToString
            LngD = efiBs.DefaultLongitude.ToString()

            utmX = efiBs.DefaultUtmX.ToString()
            utmY = efiBs.DefaultUtmY.ToString()

        End Try

        If LatD.ToString.Length > 15 Then
            LatD = LatD.ToString.Replace(".", ",").Substring(0, 15)
        Else
            LatD = LatD.ToString.Replace(".", ",")
        End If

        If LngD.ToString.Length > 15 Then
            LngD = LngD.ToString.Replace(".", ",").Substring(0, 15)
        Else
            LngD = LngD.ToString.Replace(".", ",")
        End If


        If ValidaDataColetor() = False Then

            MsgBox("A Data do Coletor não confere com as Datas de Leituras do Calendário." & Chr(10) & Chr(10) & _
                   "Ajuste a Data do Coletor.", _
                   MsgBoxStyle.Critical, "Coleta de Leitura")


            pnOcorrencias.Hide()
            pnLocalizar.Hide()
            pnTeclado.Hide()
            pnLeituras.Show()

            tUC.Focus()

            Exit Sub

        End If

        If tLeitura.Text.Trim <> "" Then

            If IsNumeric(tLeitura.Text.Trim) = False Then

                MsgBox("O campo LEITURA só permite digitar números.", MsgBoxStyle.Critical, "Coleta de Leitura")

                pnOcorrencias.Hide()
                pnLocalizar.Hide()
                pnTeclado.Hide()
                pnLeituras.Show()

                tUC.Focus()

                Exit Sub

            End If

            comando = "Select LeitMin, LeitMax From Leituras " & _
                      "Where Uc = '" & tUC.Text & "'"

            conn.AbreConexao()

            dr = conn.PreencheDataReader(comando)

            If dr.Read() = True Then

                If Convert.ToInt32(tLeitura.Text.Trim) < Convert.ToInt32(dr.GetValue(0)) Or _
                   Convert.ToInt32(tLeitura.Text.Trim) > Convert.ToInt32(dr.GetValue(1)) Then

                    If MsgBox("Leitura não corresponde com a esperada." & Chr(10) & Chr(10) & _
                              "Confirma a Leitura?", MsgBoxStyle.Critical + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Confirmação de Leitura") = MsgBoxResult.No Then

                        dr.Close()

                        comando = "Select AcertosLeit From Leituras " & _
                                  "Where Uc = '" & tUC.Text & "'"

                        conn.AbreConexao()

                        dr = conn.PreencheDataReader(comando)

                        If dr.Read() = True Then

                            acertos = dr.GetValue(0) + 1

                            dr.Close()

                            comando = "Update Leituras Set AcertosLeit = " & acertos & " " & _
                                      "Where Uc = '" & tUC.Text & "'"

                            conn.ExecutaComandoSQL(comando)

                        End If

                        chCamera = False

                        conn.FechaConexao()

                        pnOcorrencias.Hide()
                        pnLocalizar.Hide()
                        pnTeclado.Hide()
                        pnLeituras.Show()

                        tLeitura.Focus()

                        Exit Sub

                    Else

                        prmCamera = tUC.Text.PadLeft(6, "0") & Format(dtGPS, "MMyyyy")
                        chCamera = True

                    End If

                End If

                dr.Close()

                LatD = LatD.ToString.Replace(".", ",")
                LngD = LngD.ToString.Replace(".", ",")

                comando = "Update Leituras " & _
                          "Set LeituraAtual = '" & tLeitura.Text.Trim & "', " & _
                          "DataLeitura = '" & dtLeit & "', " & _
                          "HoraLeitura = '" & hrLeit & "', " & _
                          "Latitude = '" & LatG & "', " & _
                          "Longitude = '" & LngG & "', " & _
                          "LatDegress = '" & LatD & "', " & _
                          "LngDegress = '" & LngD & "', " & _
                          "UTM_x = '" & utmX & "', " & _
                          "UTM_y = '" & utmY & "', " & _
                          "DtHrSat = '" & Format(dtGPS, "yyyy-MM-dd HH:mm:ss") & "', " & _
                          "IdFoto = '" & prmCamera & "' " & _
                          "Where Uc = '" & tUC.Text & "'"

                Try

                    conn.AbreConexao()

                    conn.ExecutaComandoSQL(comando)

                    AtualizaOcorrencias(dtLeit, hrLeit, tUC.Text)

                Catch ex As Exception

                    MsgBox("LEITURA não foi gravada.", MsgBoxStyle.Critical, "Erro")

                    conn.FechaConexao()

                    pnOcorrencias.Hide()
                    pnLocalizar.Hide()
                    pnTeclado.Hide()
                    pnLeituras.Show()

                    tUC.Focus()

                    Exit Sub

                End Try

            End If


        Else

            If cbOcr1.SelectedIndex > 0 Or cbOcr2.SelectedIndex > 0 Or _
               cbOcr3.SelectedIndex > 0 Or cbOcr4.SelectedIndex > 0 Then

                AtualizaOcorrencias(dtLeit, hrLeit, tUC.Text)

            Else

                conn.AbreConexao()

                comando = "Update Leituras " & _
                          "Set LeituraAtual = Null, DataLeitura = Null, HoraLeitura = Null, " & _
                          "Latitude = Null, Longitude = Null, " & _
                          "LatDegress = Null, LngDegress = Null, " & _
                          "UTM_x = Null, UTM_y = Null, " & _
                          "Ocorrencia1 = Null, Ocorrencia2 = Null, " & _
                          "Ocorrencia3 = Null, Ocorrencia4 = Null, " & _
                          "DtHrSat = Null, " & _
                          "IdFoto = Null " & _
                          "Where Uc = '" & tUC.Text & "'"

                conn.ExecutaComandoSQL(comando)

                conn.FechaConexao()

                MsgBox("Leitura e/ou Ocorrência não informada.", _
                       MsgBoxStyle.Critical, "Confirmação de Leitura")

                bOcorrencias.BackColor = Color.Green
                bOcorrencias.ForeColor = Color.White

                pnOcorrencias.Hide()
                pnLocalizar.Hide()
                pnTeclado.Hide()
                pnLeituras.Show()

                tUC.Focus()

                Exit Sub

            End If

        End If

        dtLeit = Nothing
        hrLeit = Nothing
        comando = Nothing
        acertos = Nothing

        conn.FechaConexao()

        dr = Nothing

        pnOcorrencias.Hide()
        pnLocalizar.Hide()
        pnTeclado.Hide()
        pnLeituras.Show()

        DirecaoRegistro(1, 0)

        Try

            If chCamera = True Then

                Dim frm As New EFITransmissao.FrmCamera
                frm.Show()

                'UC(123456) - Mês Ano(009999)
                FrmCamera.ObterNomenclatura(prmCamera)

            End If

        Catch ex As Exception
            MessageBox.Show("Não foi possível exibir a câmera.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
        End Try

    End Sub

    Private Sub AtualizaOcorrencias(ByVal dLeit As String, ByVal hLeit As String, ByVal uc As String)
        Dim sql As String = Nothing
        Dim Ocr1 As String = Nothing
        Dim Ocr2 As String = Nothing
        Dim Ocr3 As String = Nothing
        Dim Ocr4 As String = Nothing

        conn.AbreConexao()

        sql = "Update Leituras " & _
                  "Set Ocorrencia1 = Null, Ocorrencia2 = Null, Ocorrencia3 = Null, Ocorrencia4 = Null " & _
                  "Where Uc = '" & uc & "'"

        Try

            conn.ExecutaComandoSQL(sql)

            If cbOcr1.SelectedIndex > 0 Then
                Ocr1 = cbOcr1.Text.Substring(0, 2)
            Else
                Ocr1 = Nothing
            End If

            If cbOcr2.SelectedIndex > 0 Then
                Ocr2 = cbOcr2.Text.Substring(0, 2)
            Else
                Ocr2 = Nothing
            End If

            If cbOcr3.SelectedIndex > 0 Then
                Ocr3 = cbOcr3.Text.Substring(0, 2)
            Else
                Ocr3 = Nothing
            End If

            If cbOcr4.SelectedIndex > 0 Then
                Ocr4 = cbOcr4.Text.Substring(0, 2)
            Else
                Ocr4 = Nothing
            End If

            LatD = LatD.ToString.Replace(".", ",")
            LngD = LngD.ToString.Replace(".", ",")

            sql = "Update Leituras " & _
                      "Set Ocorrencia1 = " & IIf(Ocr1 = Nothing, "Null", "'" & Ocr1 & "'") & ", " & _
                          "Ocorrencia2 = " & IIf(Ocr2 = Nothing, "Null", "'" & Ocr2 & "'") & ", " & _
                          "Ocorrencia3 = " & IIf(Ocr3 = Nothing, "Null", "'" & Ocr3 & "'") & ", " & _
                          "Ocorrencia4 = " & IIf(Ocr4 = Nothing, "Null", "'" & Ocr4 & "'") & ", " & _
                          "DataLeitura = '" & dLeit & "', " & _
                          "HoraLeitura = '" & hLeit & "', " & _
                          "Latitude = '" & LatG & "', " & _
                          "Longitude = '" & LngG & "', " & _
                          "LatDegress = '" & LatD & "', " & _
                          "LngDegress = '" & LngD & "', " & _
                          "UTM_x = '" & utmX & "', " & _
                          "UTM_y = '" & utmY & "', " & _
                          "DtHrSat = '" & Format(dtGPS, "yyyy-MM-dd HH:mm:ss") & "', " & _
                          "IdFoto = '" & prmCamera & "' " & _
                      "Where Uc = '" & uc & "'"

            conn.ExecutaComandoSQL(sql)

            sql = "Update Controle Set RoteiroRecebido = 1, LeiturasEnviadas = 0"
            conn.ExecutaComandoSQL(sql)

            If GpsBase = False Then

                MsgBox("O GPS está desconfigurado ou sem sinal!", MsgBoxStyle.Critical, "Coleta de Leitura")

            End If

        Catch ex As Exception

            MsgBox("Erro na Gravação do registro.", MsgBoxStyle.Critical, "Coleta de Leitura")

        End Try

        conn.FechaConexao()

        sql = Nothing
        Ocr1 = Nothing
        Ocr2 = Nothing
        Ocr3 = Nothing
        Ocr4 = Nothing

    End Sub

    Private Sub MenuSair_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuSair.Click

        DesligarGPS()

        Me.Close()

    End Sub

    Protected Overrides Sub Finalize()

        MyBase.Finalize()

    End Sub

    Private Sub MenuSobre_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuSobre.Click

        Dim frm As New EFITransmissao.FrmSobre
        frm.Show()

        'MsgBox("EFI - Sulgipe" & Chr(10) & Chr(10) & "Versão 1.0", MsgBoxStyle.Information, "Coleta de Leituras")

    End Sub

    Private Sub MenuColetar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuColetar.Click
        Dim sql As String
        Dim reg As Integer
        Dim pri As Integer = 0
        Dim ult As Integer = 0
        Dim dr As SqlCeDataReader = Nothing

        LigarGPS()

        PesqAtiva = False
        ConfigPorta = False

        pnTeclado.Hide()

        InputPanelTeclado.Enabled = False

        lbl_Contador.Visible = False

        lsf.Clear()

        If ValidaDataColetor() = False Then

            MsgBox("A Data do Coletor não confere com as Datas de Leituras do Calendário." & Chr(10) & Chr(10) & _
                   "Ajuste a Data do Coletor.", _
                   MsgBoxStyle.Critical, "Coleta de Leitura")

            Exit Sub

        End If

        sql = "Select Min(IdLeit), Max(IdLeit) From Leituras"

        conn.AbreConexao()

        dr = conn.PreencheDataReader(sql)

        If dr.Read() = True Then

            Try

                reg = dr.GetValue(0)
                pri = dr.GetValue(0)
                ult = dr.GetValue(1)

                numReg = ult

            Catch ex As Exception

                reg = Nothing
                sql = Nothing
                pri = Nothing
                ult = Nothing

                dr.Close()
                dr.Dispose()
                conn.FechaConexao()

                MsgBox("Roteiro ainda não foi Importado.", MsgBoxStyle.Exclamation, "Coleta de Leituras")

                Exit Sub

            End Try

            dr.Close()

            Try

                sql = "Select * From Leituras Where IdLeit = " & reg

                dr = conn.PreencheDataReader(sql)

                dr.Read()

                PreencheControle(dr)

            Catch ex As Exception

                reg = Nothing
                sql = Nothing
                pri = Nothing
                ult = Nothing

                dr.Close()
                dr.Dispose()
                conn.FechaConexao()

                MsgBox("Erro na leitura do arquivo.", MsgBoxStyle.Critical, "Coleta de Leituras")
                Exit Sub

            End Try

            coletaAtiva = True

            MenuFaltas.Enabled = True
            MenuLocalizar.Enabled = True
            'MenuSobre.Enabled = False

            pnOcorrencias.Hide()
            pnLocalizar.Hide()
            pnTeclado.Hide()
            pnLogin.Hide()
            pnLeituras.Show()

        Else

            MsgBox("Roteiro ainda não foi Importado.", MsgBoxStyle.Exclamation, "Coleta de Leituras")

        End If

        lbl_RegAtual.Text = FormatNumber(pri, 0, TriState.False, TriState.False, TriState.True)
        lbl_TotReg.Text = "de " & FormatNumber(ult, 0, TriState.False, TriState.False, TriState.True)

        lbl_Contador.Text = lbl_RegAtual.Text & " " & lbl_TotReg.Text

        reg = Nothing
        sql = Nothing
        pri = Nothing
        ult = Nothing

        dr.Close()
        dr.Dispose()
        conn.FechaConexao()

    End Sub

    Private Sub EFI_Activated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Activated

        If abertura = False Then

            pnLeituras.Hide()
            pnOcorrencias.Hide()
            pnLocalizar.Hide()
            pnTeclado.Hide()
            pnLogin.Hide()

            bRetornar.Visible = False
            lbl_Contador.Visible = False

            abertura = True

        End If

        conn.FechaConexao()

    End Sub

    Private Sub Faltas()
        Dim sql As String
        Dim reg As Integer = 0
        Dim dr As SqlCeDataReader = Nothing

        lbl_Contador.Visible = False

        lsf.Clear()

        fts = 0

        Try

            sql = "Select Count(UC) From Leituras Where DataLeitura is Null"

            conn.AbreConexao()

            dr = conn.PreencheDataReader(sql)

            If dr.Read() = True Then

                fts = dr.GetValue(0)

                dr.Close()

                conn.FechaConexao()

            End If

            If fts = 0 Then

                MsgBox("Todas as leituras já foram coletadas.", _
                       MsgBoxStyle.Information, "Coleta de Leituras")

            Else

                If MsgBox(IIf(fts > 1, "Faltam ", "Falta ") & FormatNumber(fts, 0, TriState.False, TriState.False, TriState.True) & IIf(fts > 1, " leituras.", " leitura.") & Chr(10) & "Deseja consultar?", _
                          MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Leituras a Coletar") = MsgBoxResult.Yes Then

                    sql = "Select IdLeit From Leituras Where DataLeitura is Null Order By IdLeit"

                    conn.AbreConexao()

                    dr = conn.PreencheDataReader(sql)

                    Do While dr.Read() = True

                        lsf.Add(dr.GetValue(0))

                    Loop

                    dr.Close()

                    DirecaoRegistro(4, lsf.First)

                End If

            End If

        Catch ex As Exception

            lsf.Clear()

            MsgBox("Erro na leitura do arquivo.", MsgBoxStyle.Critical, "Coleta de Leituras")

        End Try

        fts = Nothing
        reg = Nothing
        sql = Nothing

        dr.Dispose()
        conn.FechaConexao()

        pnOcorrencias.Hide()
        pnLocalizar.Hide()
        pnTeclado.Hide()
        pnLeituras.Show()

    End Sub

    Private Sub Localizar()
        Dim sql As String = Nothing
        Dim info As String = Nothing
        Dim tBase As String = Nothing
        Dim tPesq As String = Nothing
        Dim dPesq As String = Nothing
        Dim cp As Integer = 0
        Dim dr As SqlCeDataReader = Nothing

        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()

        lbl_Contador.Visible = False

        lsf.Clear()

        If tPesquisa.Text.Trim = "" Then

            Exit Sub

        End If

        Select Case IdPesq

            Case Is = 1

                tPesq = "Medidor"
                dPesq = "Medidor"
                info = tPesquisa.Text.Trim.PadLeft(12, "0")

            Case Is = 2

                tPesq = "Uc"
                dPesq = "UC"
                info = tPesquisa.Text.Trim.PadLeft(6, "0")

            Case Is = 3

                tPesq = "IdLeit"
                dPesq = "Registro"

                If Not IsNumeric(tPesquisa.Text.Trim) Then

                    CancelarPesquisa()
                    Exit Sub

                End If

                info = Int(tPesquisa.Text.Trim).ToString

            Case Else

                Exit Sub

        End Select


        If IdPesq = 3 Then

            sql = "Select * From Leituras Where " & tPesq & " = " & CInt(info)

        Else

            sql = "Select * From Leituras Where " & tPesq & " = '" & info & "'"

        End If

        conn.AbreConexao()

        dr = conn.PreencheDataReader(sql)

        Try

            dr.Read()

            tBase = dr.Item(tPesq).ToString()

            cp = dr.Item("Idleit")

            If tBase = info Then

                AtualizaControlePesquisa(CInt(lbl_RegAtual.Text))

                MsgBox("Registro localizado.", MsgBoxStyle.Information, "Coleta de Leituras")

                DirecaoRegistro(4, cp)

                bRetornar.Visible = True

                bOcorrencias.Enabled = True

            Else

                MsgBox(dPesq & " não localizad" & IIf(IdPesq = 2, "a!", "o!"), _
                       MsgBoxStyle.Critical, "Coleta de Leituras")

            End If

        Catch ex As Exception

            MsgBox(dPesq & " não localizad" & IIf(IdPesq = 2, "a!", "o!"), _
                   MsgBoxStyle.Critical, "Coleta de Leituras")

        End Try

        PesqAtiva = False

        InputPanelTeclado.Enabled = False

        lbl_Contador.Visible = False

        pnLocalizar.Hide()
        pnOcorrencias.Hide()
        pnTeclado.Hide()
        pnLeituras.Show()

        bOcorrencias.Enabled = True

        bRetornar.Focus()

        tBase = Nothing
        tPesq = Nothing
        info = Nothing
        sql = Nothing

        dr.Close()
        dr.Dispose()
        conn.FechaConexao()

    End Sub

    Private Sub PreencheControle(ByVal drc As SqlCeDataReader)
        Dim x As Integer = 0
        Dim vl As String = Nothing
        Dim comp As String = ""
        Dim mun As String = ""

        cbOcr1.DataSource = efiMt.GetListOcorrencias(0, 0, 0)
        cbOcr2.DataSource = efiMt.GetListOcorrencias(0, 0, 0)
        cbOcr3.DataSource = efiMt.GetListOcorrencias(0, 0, 0)
        cbOcr4.DataSource = efiMt.GetListOcorrencias(0, 0, 0)

        For x = 1 To drc.FieldCount - 1

            vl = IIf(drc.GetValue(x).ToString.Trim <> "", drc.GetValue(x), "")

            Select Case x

                Case Is = 1

                    tEndereco.Text = vl

                Case Is = 2

                    tFase.Text = efiMt.DescFase(vl)

                Case Is = 3
                    tMedidor.Text = Convert.ToDouble(vl).ToString()

                Case Is = 4
                    tConstante.Text = vl

                Case Is = 6
                    If vl <> "" Then
                        tLeitura.Text = Convert.ToDouble(vl).ToString
                    Else
                        tLeitura.Text = ""
                    End If

                Case Is = 7

                    tClasse.Text = efiMt.ClasseConsumo(vl)

                Case Is = 10

                    If vl <> "" Then
                        cbOcr1.Text = CInt(vl).ToString.PadLeft(2, "0") & "-" & efiMt.OcorrenciaLeitura(CInt(vl))
                    End If

                Case Is = 11

                    If vl <> "" Then
                        cbOcr2.Text = CInt(vl).ToString.PadLeft(2, "0") & "-" & efiMt.OcorrenciaLeitura(CInt(vl))
                    End If

                Case Is = 12

                    If vl <> "" Then
                        cbOcr3.Text = CInt(vl).ToString.PadLeft(2, "0") & "-" & efiMt.OcorrenciaLeitura(CInt(vl))
                    End If

                Case Is = 13

                    If vl <> "" Then
                        cbOcr4.Text = CInt(vl).ToString.PadLeft(2, "0") & "-" & efiMt.OcorrenciaLeitura(CInt(vl))
                    End If

                Case Is = 16

                    tUC.Text = vl

                Case Is = 23

                    tConsumidor.Text = vl

                Case Is = 24

                    If vl <> "" Then

                        mun = efiMt.Municipio(CInt(vl))

                    End If

                Case Is = 25

                    If vl = "N" Then

                        lbl_Ligado.Visible = True

                    Else

                        lbl_Ligado.Visible = False

                    End If

                Case Is = 26

                    If lbl_Ligado.Visible = True Then

                        If vl <> "" Then
                            lbl_Ligado.Text = efiMt.MotivoDesligamento(CInt(vl))
                        End If

                    Else

                        lbl_Ligado.Text = " "

                    End If

                Case Is = 27

                    If vl = "00" Or vl = "25" Or vl = "" Then

                        lbl_Ocorrencia_Ant.Visible = False

                    Else

                        lbl_Ocorrencia_Ant.Visible = True

                        lbl_Ocorrencia_Ant.Text = efiMt.OcorrenciaLeitura(CInt(vl))

                    End If

                Case Is = 28

                    tRota.Text = vl

                Case Is = 31

                    If vl <> "" Then

                        tEndereco.Text = tEndereco.Text & " - " & vl

                    End If

            End Select

        Next

        If tEndereco.Text.Trim <> "" Then

            tEndereco.Text = tEndereco.Text & "  " & mun

        End If

        bOcorrencias.Enabled = True

        If cbOcr1.Text <> "" Then
            bOcorrencias.BackColor = Color.Firebrick
        Else
            bOcorrencias.BackColor = Color.Green
        End If

        If tLeitura.Text = "" Then

            tUC.Focus()

        End If

    End Sub

    Private Sub AtualizaControle(ByVal id As Integer)
        Dim sql As String

        sql = "Update Controle set Idleitura = " & id
        conn.ExecutaComandoSQL(sql)
        sql = Nothing

    End Sub

    Private Sub AtualizaControlePesquisa(ByVal id As Integer)
        Dim sql As String

        sql = "Update Controle set IdPesquisa = " & id
        conn.ExecutaComandoSQL(sql)
        sql = Nothing

    End Sub

    Private Sub bAnterior_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAnterior.Click

        DirecaoRegistro(0, 0)

    End Sub

    Private Sub bProximo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bProximo.Click

        DirecaoRegistro(1, 0)

    End Sub

    Private Sub bInicio_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bInicio.Click

        DirecaoRegistro(2, 0)

    End Sub

    Private Sub bFinal_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bFinal.Click

        DirecaoRegistro(3, 0)

    End Sub

    Private Sub bRetornar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bRetornar.Click

        lsf.Clear()

        DirecaoRegistro(5, 0)

    End Sub

    Private Sub DirecaoRegistro(ByVal direcao As Integer, ByVal pos As Integer)
        'Direção:
        '0 - Retornar 1 registro
        '1 - Avançar 1 registro
        '2 - Primeiro registro
        '3 - Último registro
        '4 - Vai ao registro informado, passando a posição desejada
        '5 - Voltar ao registro após a pesquisa (Último coletado)
        '6 - Permanece no registro atual

        Dim sql As String = Nothing
        Dim dr As SqlCeDataReader
        Dim reg As Integer = 0
        Dim pri As Integer = 0
        Dim ult As Integer = 0
        Dim ret As Integer = 0

        bRetornar.Visible = False

        lbl_Contador.Visible = False

        conn.AbreConexao()

        sql = "Select IdLeitura, IdPesquisa From Controle"

        dr = conn.PreencheDataReader(sql)

        If dr.Read() = True Then

            'Registro atual
            reg = dr.GetValue(0)

            'Último registro acessado antes da pesquisa
            ret = dr.GetValue(1)

            dr.Close()

            Try

                If lsf.Count > 0 Then

                    pri = lsf.First
                    ult = lsf.Last

                    Select Case direcao
                        Case Is = 0
                            If reg > pri Then
                                reg = lsf.Item(plist - 1)
                            End If
                        Case Is = 1
                            If reg < ult Then
                                reg = lsf.Item(plist + 1)
                            End If
                        Case Is = 2
                            reg = pri
                            'MsgBox("Primeiro registro de faltas.", MsgBoxStyle.Information, "Coleta de Leituras")
                        Case Is = 3
                            reg = ult
                            'MsgBox("Último registro de faltas.", MsgBoxStyle.Information, "Coleta de Leituras")
                        Case Is = 4
                            reg = pos
                        Case Is = 5
                            reg = ret
                    End Select

                Else

                    'Primeiro e Último Registros
                    sql = "Select Min(IdLeit), Max(IdLeit) From Leituras"
                    dr = conn.PreencheDataReader(sql)
                    If dr.Read() = True Then
                        pri = dr.GetValue(0)
                        ult = dr.GetValue(1)
                    End If

                    dr.Close()

                    Select Case direcao
                        Case Is = 0
                            If reg > pri Then
                                reg = reg - 1
                            End If
                        Case Is = 1
                            If reg < ult Then
                                reg = reg + 1
                            End If
                        Case Is = 2
                            reg = pri
                            'MsgBox("Primeiro registro.", MsgBoxStyle.Information, "Coleta de Leituras")
                        Case Is = 3
                            reg = ult
                            'MsgBox("Último registro.", MsgBoxStyle.Information, "Coleta de Leituras")
                        Case Is = 4
                            reg = pos
                        Case Is = 5
                            reg = ret
                    End Select

                End If

                sql = "Select * From Leituras Where IdLeit = " & reg

                dr = conn.PreencheDataReader(sql)

                dr.Read()

                PreencheControle(dr)

                If lsf.Count > 0 Then

                    plist = posicaoList(reg)

                    lbl_RegAtual.Text = FormatNumber((plist + 1), 0, TriState.False, TriState.False, TriState.True)
                    lbl_TotReg.Text = "de " & FormatNumber(lsf.Count, 0, TriState.False, TriState.False, TriState.True)

                    bRetornar.Visible = True

                Else

                    lbl_RegAtual.Text = FormatNumber(reg, 0, TriState.False, TriState.False, TriState.True)
                    lbl_TotReg.Text = "de " & FormatNumber(ult, 0, TriState.False, TriState.False, TriState.True)


                    bRetornar.Visible = False

                End If

                lbl_Contador.Text = lbl_RegAtual.Text & " " & lbl_TotReg.Text

                AtualizaControle(reg)

            Catch ex As Exception

                reg = Nothing
                ult = Nothing
                sql = Nothing

                dr.Close()
                dr.Dispose()
                conn.FechaConexao()

                MsgBox("Erro na leitura do arquivo.", MsgBoxStyle.Critical, "Coleta de Leituras")
                Exit Sub

            End Try

            pnOcorrencias.Hide()
            pnLocalizar.Hide()
            pnTeclado.Hide()
            pnLeituras.Show()

            tUC.Focus()

        End If

        reg = Nothing
        sql = Nothing

        dr.Close()
        dr.Dispose()

        conn.FechaConexao()

    End Sub

    Private Sub bOcorrencias_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bOcorrencias.Click

        lbl_Contador.Visible = False

        If pnOcorrencias.Visible = False Then

            pnTeclado.Hide()
            pnLocalizar.Hide()
            pnOcorrencias.Visible = True
            pnOcorrencias.Show()

            If cbOcr1.SelectedIndex = 0 Then
                cbOcr1.Focus()
            ElseIf cbOcr2.SelectedIndex = 0 Then
                cbOcr2.Focus()
            ElseIf cbOcr3.SelectedIndex = 0 Then
                cbOcr3.Focus()
            Else
                cbOcr4.Focus()
            End If

        Else

            pnOcorrencias.Hide()
            pnOcorrencias.Visible = False

            If tLeitura.Text.Trim <> "" Then
                bGravar.Focus()
            Else
                tUC.Focus()
            End If

        End If

    End Sub

    Private Sub lkLimpar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkLimpar.Click

        If cbOcr4.SelectedIndex > 0 Then
            cbOcr4.SelectedIndex = 0
            cbOcr4.Focus()
        ElseIf cbOcr3.SelectedIndex > 0 Then
            cbOcr3.SelectedIndex = 0
            cbOcr3.Focus()
        ElseIf cbOcr2.SelectedIndex > 0 Then
            cbOcr2.SelectedIndex = 0
            cbOcr2.Focus()
        ElseIf cbOcr1.SelectedIndex > 0 Then
            cbOcr1.SelectedIndex = 0
            cbOcr1.Focus()
        Else
            pnOcorrencias.Hide()
        End If

    End Sub

    Private Sub cbOcr1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbOcr1.SelectedIndexChanged

        If cbOcr1.SelectedIndex > 0 Then

            cbOcr2.Visible = True
            lblMens2.Visible = True
            cbOcr2.DataSource = efiMt.GetListOcorrencias(cbOcr1.SelectedIndex, 0, 0)
            cbOcr2.Focus()

        Else

            cbOcr2.Visible = False
            cbOcr3.Visible = False
            cbOcr4.Visible = False
            lblMens2.Visible = False
            lblMens3.Visible = False
            lblMens4.Visible = False

        End If

    End Sub

    Private Sub cbOcr2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbOcr2.SelectedIndexChanged

        If cbOcr2.SelectedIndex > 0 Then

            cbOcr3.Visible = True
            lblMens3.Visible = True
            cbOcr3.DataSource = efiMt.GetListOcorrencias(cbOcr1.SelectedIndex, cbOcr2.SelectedIndex, 0)
            cbOcr3.Focus()

        Else

            cbOcr3.Visible = False
            cbOcr4.Visible = False
            lblMens3.Visible = False
            lblMens4.Visible = False

        End If

    End Sub

    Private Sub cbOcr3_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbOcr3.SelectedIndexChanged

        If cbOcr3.SelectedIndex > 0 Then

            cbOcr4.Visible = True
            lblMens4.Visible = True
            cbOcr4.DataSource = efiMt.GetListOcorrencias(cbOcr1.SelectedIndex, cbOcr2.SelectedIndex, cbOcr3.SelectedIndex)
            cbOcr4.Focus()

        Else

            cbOcr4.Visible = False
            lblMens4.Visible = False

        End If

    End Sub

    Private Sub LerNovoArquivoTxt()
        Dim sql As String = Nothing
        Dim dr As SqlCeDataReader = Nothing
        Dim tReg As Integer = 0

        PesqAtiva = False
        ConfigPorta = False
        lbl_Contador.Visible = False

        Cursor.Current = Cursors.WaitCursor

        CriarArqGPS()

        If LerArquivoTexto() = True Then

            File.Delete(arquivo)
            File.Delete(arqControle)

            conn.AbreConexao()

            sql = "Select Max(IdLeit) From Leituras"
            dr = conn.PreencheDataReader(sql)

            If dr.Read() = True Then

                tReg = dr.GetValue(0)

            End If

            dr.Close()

            If OrdenarRoteiro(tReg) = True Then

                conn.AbreConexao()

                sql = "Update Controle Set RoteiroRecebido = 1"
                conn.ExecutaComandoSQL(sql)

                'Adaptação / C#:
                Dim ent As New EFITransmissao.Entidade.ListaMinMax()

                sql = "Select Min(SeqLeitura) as Min, Max(SeqLeitura) as Max From Leituras"
                dr = conn.PreencheDataReader(sql)

                If dr.Read() = True Then

                    ent.MinOrdem = dr.GetValue(0)
                    ent.MaxOrdem = dr.GetValue(1)

                End If

                dr.Close()

                If EFITransmissao.Interface.InterTransmissao.RoteiroDisponivel(txtMatricula_pnLogin.Text, ent) = True Then

                    MsgBox("Roteiro atualizado com sucesso." & Chr(10) & Chr(10) & _
                       "Total de Registros: " & FormatNumber(tReg, 0, TriState.False, TriState.False, TriState.True), _
                       MsgBoxStyle.Information, "Coleta de Leituras")

                    'MenuReceber.Enabled = False
                    'MenuEnviar.Enabled = True
                    MenuColetar.Enabled = True
                    MenuFaltas.Enabled = False
                    MenuLocalizar.Enabled = False

                Else
                    MessageBox.Show("O arquivo disponível não corresponde ao esperado!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)
                End If
                pnLogin.Hide()

            Else

                sql = "Update Controle Set RoteiroRecebido = 0"
                conn.AbreConexao()
                conn.ExecutaComandoSQL(sql)

                MsgBox("Erro na importação do Roteiro." & Chr(10) & Chr(10) & _
                       "Entre em contato com o Setor de TI", _
                       MsgBoxStyle.Critical, "Coleta de Leituras")

                'MenuReceber.Enabled = True
                MenuColetar.Enabled = False
                'MenuEnviar.Enabled = False
                MenuFaltas.Enabled = False
                MenuLocalizar.Enabled = False

            End If

        Else

            sql = "Update Controle Set RoteiroRecebido = 0"
            conn.AbreConexao()
            conn.ExecutaComandoSQL(sql)

            MsgBox("Erro na importação do Roteiro." & Chr(10) & Chr(10) & _
                   "Entre em contato com o Setor de TI", _
                   MsgBoxStyle.Critical, "Coleta de Leituras")

            MenuColetar.Enabled = False
            MenuFaltas.Enabled = False
            MenuLocalizar.Enabled = False

            InputPanelTeclado.Enabled = False
            pnLogin.Hide()

        End If

        conn.FechaConexao()

        Cursor.Current = Cursors.Default

    End Sub

    Private Function GerarArquivoLeiturasParaEnvio() As Boolean
        Dim sql As String = Nothing
        Dim dr As SqlCeDataReader = Nothing
        Dim tReg As Integer = 0
        Dim tLeit As Integer = 0

        Dim retorno As Boolean

        DesligarGPS()

        lbl_Contador.Visible = False

        Try

            If File.Exists(arquivo) = True Then

                File.Delete(arquivo)

            End If

            conn.AbreConexao()

            sql = "Select Count(UC) From Leituras"

            dr = conn.PreencheDataReader(sql)

            If dr.Read() = True Then

                tReg = dr.GetValue(0)

            End If

            dr.Close()

            sql = "Select Count(UC) From Leituras Where DataLeitura Is Not Null"

            dr = conn.PreencheDataReader(sql)

            If dr.Read() = True Then

                tLeit = dr.GetValue(0)

                If tLeit = 0 Then

                    MsgBox("Ainda não é possível enviar o arquivo porque nenhuma leitura foi coletada.", MsgBoxStyle.Critical, "Coleta de Leituras")
                    dr.Close()
                    tLeit = Nothing
                    tReg = Nothing
                    sql = Nothing
                    conn.FechaConexao()
                    Return False

                ElseIf (tLeit < (tReg / 2)) Then

                    If MsgBox("Total de Faltas está excessivo, deseja enviar mesmo assim?", _
                              MsgBoxStyle.Critical + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Coleta de Leituras") = MsgBoxResult.No Then

                        dr.Close()
                        tLeit = Nothing
                        tReg = Nothing
                        sql = Nothing
                        conn.FechaConexao()
                        Return False

                    End If

                ElseIf MsgBox("Confirma o envio do arquivo de Leituras?", _
                    MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Coleta de Leituras") = MsgBoxResult.No Then

                    dr.Close()
                    tLeit = Nothing
                    tReg = Nothing
                    sql = Nothing
                    conn.FechaConexao()
                    Return False

                End If

            End If

            dr.Close()

            If GeraArquivoTexto() = True Then

                If GeraArquivoTextoControle() = True Then

                    sql = "Update Controle Set LeiturasEnviadas = 1"
                    conn.ExecutaComandoSQL(sql)

                    MsgBox("Arquivo de Leituras gerado com sucesso.", _
                           MsgBoxStyle.Information, "Coleta de Leituras")
                    retorno = True
                Else

                    MsgBox("Erro na geração do Arquivo de Leituras." & Chr(10) & Chr(10) & _
                           "Entre em contato com o Setor de TI", _
                           MsgBoxStyle.Critical, "Coleta de Leituras")

                    retorno = False
                End If

            Else

                MsgBox("Erro na geração do Arquivo de Leituras." & Chr(10) & Chr(10) & _
                       "Entre em contato com o Setor de TI", _
                       MsgBoxStyle.Critical, "Coleta de Leituras")

                retorno = False
            End If

        Catch ex As Exception

            MsgBox("Erro na geração do Arquivo de Leituras." & Chr(10) & Chr(10) & _
                   "Entre em contato com o Setor de TI", _
                   MsgBoxStyle.Critical, "Coleta de Leituras")

            retorno = False

        End Try

        conn.FechaConexao()

        Return retorno

    End Function

    Private Function GeraArquivoTexto() As Boolean
        'Ler dados do Banco e gerar arquivo texto de retorno
        Dim textoSW As StreamWriter 'Leitura e Gravação
        Dim dr As SqlCeDataReader = Nothing
        Dim vl As String = Nothing
        Dim sLine As String = Nothing 'linha
        Dim sql As String = Nothing
        Dim tam As Integer = 0
        Dim tp As Char = Nothing
        Dim tipo As Integer = 0
        Dim col As Integer = 0

        Try

            'Arquivo de Leituras
            sql = "Select * From Leituras Order By IdLeit"

            conn.AbreConexao()

            dr = conn.PreencheDataReader(sql)

            textoSW = New StreamWriter(arquivo, False, Encoding.Default)

            Do While dr.Read() = True

                sLine = ""

                For col = 0 To (dr.FieldCount - 4)

                    vl = dr.GetValue(col).ToString()

                    Select Case col
                        Case Is = 0, 8, 9, 16
                            '[SeqLeitura]
                            '[LeitMin]
                            '[LeitMax]
                            '[Uc]
                            'Preenchimento a esquerda (com zero)
                            tipo = 1
                            tp = "0"
                            tam = 6
                        Case Is = 3, 30, 38
                            '[Medidor]
                            '[MedidorRetirado]
                            '[MedidorAlt]
                            'Preenchimento a esquerda (com zero)
                            tipo = 1
                            tp = "0"
                            tam = 12
                        Case Is = 4, 24, 26, 27
                            '[Constante]
                            '[IdRegiao]
                            '[IdMotivoDeslig]
                            '[OcorrenciaAnt]
                            'Preenchimento a esquerda (com zero)
                            tipo = 1
                            tp = "0"
                            tam = 2
                        Case Is = 5, 6
                            '[LeituraAnterior]
                            '[LeituraAtual]
                            'Preenchimento a esquerda (com zero)
                            If vl = "" Then
                                tp = " "
                            Else
                                tp = "0"
                            End If
                            tipo = 1
                            tam = 8
                        Case Is = 10, 11, 12, 13
                            '[Ocorrencia1]
                            '[Ocorrencia2]
                            '[Ocorrencia3]
                            '[Ocorrencia4]
                            'Preenchimento a esquerda (com zero)
                            tipo = 1
                            tp = "0"
                            tam = 3
                        Case Is = 28, 29
                            '[IdRota]
                            '[AcertosLeit]
                            'Preenchimento a esquerda (com zero)
                            tipo = 1
                            tp = "0"
                            tam = 4
                        Case Is = 36, 37
                            '[UTM_x]
                            '[UTM_y]
                            'Preenchimento a esquerda (com zero)
                            tipo = 1
                            tp = "0"
                            tam = 15
                        Case Is = 1
                            '[Endereco]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 55
                        Case Is = 14
                            '[DataLeitura]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 8
                        Case Is = 15
                            '[HoraLeitura]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 5
                        Case Is = 2, 7, 17, 18, 19, 20, 21, 25
                            '[Fase]
                            '[Classe]
                            '[Fixo1]
                            '[Fixo2]
                            '[Fixo3]
                            '[Fixo4]
                            '[Fixo5]
                            '[Ligado]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 1
                        Case Is = 22
                            '[Fixo6]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 6
                        Case Is = 23
                            '[Nome]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 100
                        Case Is = 31
                            '[Complemento]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 45
                        Case Is = 32, 33, 34, 35
                            '[Latitude]
                            '[Longitude]
                            '[LatDegress]
                            '[LngDegress]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 15
                        Case Is = 39, 40, 41
                            '[Fabricante]
                            '[Marca]
                            '[Modelo]
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 20
                    End Select

                    If tipo = 0 Then
                        vl = vl.PadRight(tam, tp)
                    Else
                        vl = vl.PadLeft(tam, tp)
                    End If

                    sLine = sLine & vl

                    If col < (dr.FieldCount - 4) Then
                        sLine = sLine & "|"
                    End If

                Next


                '[DataHoraSatélite] - Preenchimento a direita com espaços vazios
                vl = dr.GetValue(43).ToString()

                Try

                    If vl.ToString.Trim <> "" Then
                        vl = Format(Convert.ToDateTime(vl), "dd/MM/yyyy HH:mm:ss")
                    End If

                Catch ex_vl As Exception

                    vl = ""

                End Try

                tp = " "
                tam = 19

                vl = vl.PadRight(tam, tp)
                sLine = sLine & "|" & vl


                '[IdFoto] - Preenchimento a direita com espaços vazios
                vl = dr.GetValue(44).ToString()

                If vl <> "" Then

                    If Not File.Exists(".\Program Files\EFITransmissao\Fotos\Coleta\" & vl & ".jpg") Then
                        vl = ""
                    End If

                End If

                tp = " "
                tam = 12

                vl = vl.PadRight(tam, tp)
                sLine = sLine & "|" & vl


                'Gravação das Linhas de Registros
                textoSW.WriteLine(sLine)

            Loop

            sLine = Nothing
            col = Nothing

            textoSW.Flush() 'esvazia o arquivo da memória
            textoSW.Close() 'fecha a leitura do arquivo
            textoSW.Dispose()

            sql = Nothing

        Catch ex As Exception

            Return False

        End Try

        Return True

    End Function

    Private Function GeraArquivoTextoControle() As Boolean
        'Ler dados do Banco e gerar arquivo texto de retorno
        Dim textoSW As StreamWriter 'Leitura e Gravação
        Dim dr As SqlCeDataReader = Nothing
        Dim vl As String = Nothing
        Dim sLine As String = Nothing 'linha
        Dim sql As String = Nothing
        Dim tam As Integer = 0
        Dim tp As Char = Nothing
        Dim tipo As Integer = 0
        Dim col As Integer = 0

        Try

            'Arquivo de Controle
            sql = "Select * From Controle"

            conn.AbreConexao()

            dr = conn.PreencheDataReader(sql)

            textoSW = New StreamWriter(arqControle, False, Encoding.Default)

            Do While dr.Read() = True

                sLine = ""

                For col = 4 To (dr.FieldCount - 1)

                    vl = dr.GetValue(col).ToString()

                    Select Case col
                        Case Is = 4, 5, 6
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 10
                        Case Is = 7
                            'Preenchimento a esquerda (com zeros)
                            tipo = 1
                            tp = "0"
                            tam = 2
                        Case Is = 8, 10, 11
                            'Preenchimento a esquerda (com zeros)
                            tipo = 1
                            tp = "0"
                            tam = 4
                        Case Is = 9
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 30
                        Case Is = 12
                            'Preenchimento a direta (com espaços vazios)
                            tipo = 0
                            tp = " "
                            tam = 4
                    End Select

                    If tipo = 0 Then
                        vl = vl.PadRight(tam, tp)
                    Else
                        vl = vl.PadLeft(tam, tp)
                    End If

                    sLine = sLine & vl

                    If col < (dr.FieldCount - 1) Then
                        sLine = sLine & "|"
                    End If

                Next

                textoSW.WriteLine(sLine)

            Loop

            sLine = Nothing
            col = Nothing

            textoSW.Flush() 'esvazia o arquivo da memória
            textoSW.Close() 'fecha a leitura do arquivo
            textoSW.Dispose()

            sql = Nothing

        Catch ex As Exception

            Return False

        End Try

        Return True

    End Function

    Private Function ValidaDataColetor() As Boolean
        Dim dr As SqlCeDataReader = Nothing
        Dim sql As String = Nothing
        Dim dtColetor As Long = Nothing
        Dim dtCalendarIni As Long = Nothing
        Dim dtCalendarFim As Long = Nothing
        Dim validacao As Boolean = True

        Try

            dtColetor = Format(Date.Now, "yyyyMMdd")

            sql = "Select DtLeitInicio, DtLeitFim From Controle"

            conn.AbreConexao()

            dr = conn.PreencheDataReader(sql)

            If dr.Read() = True Then

                dtCalendarIni = Format(CDate(dr.GetValue(0)), "yyyyMMdd")
                dtCalendarFim = Format(CDate(dr.GetValue(1)), "yyyyMMdd")

                If dtColetor < dtCalendarIni Or dtColetor > dtCalendarFim Then

                    validacao = False

                End If

            Else

                validacao = False

            End If

            dr.Close()

        Catch ex As Exception

            validacao = False

        Finally

            dr.Dispose()
            sql = Nothing
            dtColetor = Nothing
            dtCalendarIni = Nothing
            dtCalendarFim = Nothing

            conn.FechaConexao()

        End Try

        Return validacao

    End Function

    Private Sub MenuSistema_Popup(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuSistema.Popup
        Dim dr As SqlCeDataReader = Nothing
        Dim sql As String = Nothing
        Dim rot As Boolean = False
        Dim env As Boolean = False

        Try

            conn.AbreConexao()

            sql = "Select * From Controle"
            dr = conn.PreencheDataReader(sql)

            If dr.Read() = True Then

                rot = dr.GetValue(2)
                env = dr.GetValue(3)

                If rot = True And env = False Then

                    MenuColetar.Enabled = True

                End If

                If rot = True And env = True Then

                    MenuColetar.Enabled = True

                End If

                If rot = False And env = True Then

                    MenuColetar.Enabled = False

                End If

                If rot = False And env = False Then

                    MenuColetar.Enabled = False

                End If

            Else

                MenuColetar.Enabled = False

            End If

            conn.FechaConexao()

        Catch ex As Exception

            sql = Nothing

            dr.Close()
            dr.Dispose()
            conn.FechaConexao()

            MenuColetar.Enabled = False

        End Try

    End Sub

    Private Sub MenuLocalizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuLocalizar.Click

        PesqAtiva = True
        ConfigPorta = False

        bOcorrencias.Enabled = False

        pnOcorrencias.Hide()
        pnTeclado.Hide()
        pnLocalizar.Show()

        rdbRegistro.Checked = False
        rdbUc.Checked = False

        IdPesq = 1
        tamCtlPesq = 12

        rdbMedidor.Checked = True

        tPesquisa.Text = ""
        tPesquisa.Focus()

    End Sub

    Private Sub MenuFaltas_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFaltas.Click

        PesqAtiva = False
        ConfigPorta = False

        lbl_Contador.Visible = False

        Faltas()

    End Sub

    Private Function posicaoList(ByVal vItem As Integer) As Integer
        Dim x As Integer

        For x = 0 To lsf.Count - 1

            If lsf.Item(x) = vItem Then

                Return x

            End If

        Next

    End Function

    Private Sub tLeitura_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tLeitura.GotFocus

        InputPanelTeclado.Enabled = False

        pnOcorrencias.Hide()

        If PesqAtiva = False Then

            pnTeclado.Show()

        Else

            bCancelar.Focus()

        End If

    End Sub

    Private Sub CapturaTeclado(ByVal caracter As String)
        Dim ctl As Integer

        If PesqAtiva = True Then

            If tPesquisa.Text.Trim.Length < tamCtlPesq Then

                pteclado = tPesquisa.SelectionStart

                If Int(caracter) = 0 And pteclado = 0 Then

                    pteclado = tPesquisa.SelectionStart

                Else

                    tPesquisa.Text = InsereTexto(tPesquisa.Text, pteclado, caracter)

                    pteclado = pteclado + 1

                End If

            End If

            ctl = 1

        Else

            If tLeitura.Text.Trim.Length < 8 Then

                pteclado = tLeitura.SelectionStart

                If Int(caracter) = 0 And pteclado = 0 Then

                    pteclado = tLeitura.SelectionStart

                Else

                    tLeitura.Text = InsereTexto(tLeitura.Text, pteclado, caracter)

                    pteclado = pteclado + 1

                End If

            End If

            ctl = 0

        End If

        AtivaFocoTexto(ctl)

    End Sub

    Private Sub bt1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt1.Click

        CapturaTeclado("1")

    End Sub

    Private Sub bt2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt2.Click

        CapturaTeclado("2")

    End Sub

    Private Sub bt3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt3.Click

        CapturaTeclado("3")


    End Sub

    Private Sub bt4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt4.Click

        CapturaTeclado("4")

    End Sub

    Private Sub bt5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt5.Click

        CapturaTeclado("5")

    End Sub

    Private Sub bt6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt6.Click

        CapturaTeclado("6")

    End Sub

    Private Sub bt7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt7.Click

        CapturaTeclado("7")

    End Sub

    Private Sub bt8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt8.Click

        CapturaTeclado("8")

    End Sub

    Private Sub bt9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt9.Click

        CapturaTeclado("9")

    End Sub

    Private Sub btZero_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btZero.Click

        CapturaTeclado("0")

    End Sub

    Private Sub btLimpar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btLimpar.Click
        Dim ctl As Integer

        If PesqAtiva = True Then

            pteclado = tPesquisa.SelectionStart

            If tPesquisa.SelectedText <> "" Then

                tPesquisa.Text = RemoveTexto(tPesquisa.Text, tPesquisa.SelectedText, pteclado)

            Else

                If pteclado > 0 Then

                    tPesquisa.Text = RemoveTexto(tPesquisa.Text, pteclado)

                    pteclado = pteclado - 1

                End If

            End If

            ctl = 1

        Else

            pteclado = tLeitura.SelectionStart

            If tLeitura.SelectedText <> "" Then

                tLeitura.Text = RemoveTexto(tLeitura.Text, tLeitura.SelectedText, pteclado)

            Else

                If pteclado > 0 Then

                    tLeitura.Text = RemoveTexto(tLeitura.Text, pteclado)

                    pteclado = pteclado - 1

                End If

            End If

            ctl = 0

        End If

        AtivaFocoTexto(ctl)

    End Sub

    Private Sub btEnter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btEnter.Click

        bGravar.Focus()

        pnTeclado.Hide()

        lbl_Contador.Visible = False

    End Sub

    Private Sub btVoltar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btVoltar.Click
        Dim ctl As Integer

        If PesqAtiva = True Then

            If tPesquisa.SelectionStart > 0 Then

                pteclado = tPesquisa.SelectionStart - 1

            End If

            ctl = 1

        Else

            If tLeitura.SelectionStart > 0 Then

                pteclado = tLeitura.SelectionStart - 1

            End If

            ctl = 0

        End If

        AtivaFocoTexto(ctl)

    End Sub

    Private Sub btAvancar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btAvancar.Click
        Dim ctl As Integer

        If PesqAtiva = True Then

            If tPesquisa.SelectionStart < tamCtlPesq Then

                pteclado = tPesquisa.SelectionStart + 1

            End If

            ctl = 1

        Else

            If tLeitura.SelectionStart < 8 Then

                pteclado = tLeitura.SelectionStart + 1

            End If

            ctl = 0

        End If

        AtivaFocoTexto(ctl)

    End Sub

    Private Sub btOcultar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btOcultar.Click

        pnTeclado.Hide()
        lbl_Contador.Visible = False

    End Sub

    Private Sub tUC_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tUC.GotFocus

        lbl_Contador.Visible = False
        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()
        pnOcorrencias.Hide()

    End Sub

    Private Function RemoveTexto(ByVal txt As String, ByVal pos As Integer) As String
        Dim x As Integer
        Dim nTexto As String = ""
        Dim tam As Integer = 0

        tam = txt.Length

        For x = 0 To tam - 1

            If x <> pos - 1 Then

                nTexto = nTexto & txt.Substring(x, 1)

            End If

        Next

        Return nTexto

    End Function

    Private Function RemoveTexto(ByVal txt As String, ByVal txtSel As String, ByVal pos As Integer) As String
        Dim x As Integer
        Dim nTexto As String = ""
        Dim tam As Integer = 0
        Dim tamSel As Integer = 0

        tam = txt.Length
        tamSel = txtSel.Length

        If tam = tamSel Then

            nTexto = ""

        Else

            For x = 0 To tam - 1

                If x = pos Then

                    x = x + tamSel - 1

                Else

                    nTexto = nTexto & txt.Substring(x, 1)

                End If

            Next

        End If

        Return nTexto

    End Function

    Private Function InsereTexto(ByVal txt As String, ByVal pos As Integer, ByVal caracter As String) As String
        Dim x As Integer
        Dim nTexto As String = ""
        Dim tam As Integer = 0

        tam = txt.Length

        If tam = 0 Then

            nTexto = nTexto & caracter

        Else

            For x = 0 To tam - 1

                If x = pos Then

                    nTexto = nTexto & caracter & txt.Substring(x, 1)

                Else

                    nTexto = nTexto & txt.Substring(x, 1)

                End If

            Next

            If pos > tam - 1 Then

                nTexto = nTexto & caracter

            End If

        End If

        Return nTexto

    End Function

    Private Sub AtivaFocoTexto(ByVal ctlFoco As Integer)

        Select Case ctlFoco

            Case Is = 0

                tLeitura.Focus()

                tLeitura.SelectionStart = pteclado

                tLeitura.SelectionLength = 0

            Case Is = 1

                tPesquisa.Focus()

                tPesquisa.SelectionStart = pteclado

                tPesquisa.SelectionLength = 0

            Case Else

                tUC.Focus()

        End Select

    End Sub

    Private Sub tRota_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tRota.GotFocus

        lbl_Contador.Visible = False
        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()
        pnOcorrencias.Hide()

    End Sub

    Private Sub tFase_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tFase.GotFocus

        lbl_Contador.Visible = False
        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()
        pnOcorrencias.Hide()

    End Sub

    Private Sub tClasse_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tClasse.GotFocus

        lbl_Contador.Visible = False
        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()
        pnOcorrencias.Hide()

    End Sub

    Private Sub tConstante_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tConstante.GotFocus

        lbl_Contador.Visible = False
        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()
        pnOcorrencias.Hide()

    End Sub

    Private Sub tConsumidor_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tConsumidor.GotFocus

        lbl_Contador.Visible = False
        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()
        pnOcorrencias.Hide()

    End Sub

    Private Sub tEndereco_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tEndereco.GotFocus

        lbl_Contador.Visible = False
        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()
        pnOcorrencias.Hide()

    End Sub

    Private Sub tMedidor_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tMedidor.GotFocus

        lbl_Contador.Visible = False
        InputPanelTeclado.Enabled = False
        pnTeclado.Hide()
        pnOcorrencias.Hide()

    End Sub

    Private Sub GeraCoordenadas()
        Dim info As String = Nothing

        If newLatitude.ToString() <> "" Then

            utm = efiBs.cLLToUTM(Convert.ToDecimal(efiBs.myLatitude.ToString().Replace(".", ",")), _
                                 Convert.ToDecimal(efiBs.myLongitude.ToString().Replace(".", ",")))

            'Porta | Lat. em Graus | Long. em Graus | Lat. decimal | Long. decimal | UTM x | UTM y | Zona | Hemisfério

            info = Latitude.ToString() & "|" & _
                   Longitude.ToString() & "|" & _
                   newLatitude.ToString().Replace(",", ".") & "|" & _
                   newLongitude.ToString().Replace(",", ".") & "|" & _
                   efiMt.ValorDecimalTruncar(3, Convert.ToDouble(utm.Easting.ToString())).ToString().Replace(",", ".") & "|" & _
                   efiMt.ValorDecimalTruncar(3, Convert.ToDouble(utm.Northing.ToString())).ToString().Replace(",", ".") & "|" & _
                   utm.Zone.ToString() & "|" & _
                   If(utm.UTMLatitudeHemisphere = EfiBase.GpsCoordenadas.UTMLat.North, "N", "S")

            EscreveTxtLista(info)

        End If

    End Sub

    Private Sub EscreveTxtLista(ByVal ds As String)

        'Add coordenadas na lista.
        listGPS.Items.Add(ds)

    End Sub

    Private Sub EscreveTxtGPS()
        Dim owGPS As StreamWriter
        Dim i As Integer = 0

        owGPS = New StreamWriter(arqGPS, False, Encoding.Default)

        'Remove itens existentes no .\GPS.txt
        For Each item As Char In arqGPS
            arqGPS.Remove(0, i)
            i = i + 1
        Next

        For Each item As String In listGPS.Items

            'Escreve no .\GPS.txt
            owGPS.WriteLine(item.ToString())

        Next

        owGPS.Close()

    End Sub


    Private Sub InputPanelTeclado_EnabledChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InputPanelTeclado.EnabledChanged

        If ControleFoco() = True Then

            InputPanelTeclado.Enabled = False

            If tLeitura.Focused = True Then

                pnTeclado.Show()
                lbl_Contador.Visible = False

            ElseIf tPesquisa.Focused = True Then

                pnTeclado.Show()
                lbl_Contador.Visible = True

            Else

                pnTeclado.Hide()
                lbl_Contador.Visible = False

            End If

        End If

    End Sub

    Private Function ControleFoco() As Boolean

        If tUC.Focused = True Then Return True

        If tRota.Focused = True Then Return True

        If tEndereco.Focused = True Then Return True

        If tConsumidor.Focused = True Then Return True

        If tMedidor.Focused = True Then Return True

        If tConstante.Focused = True Then Return True

        If tLeitura.Focused = True Then Return True

        If tClasse.Focused = True Then Return True

        If tFase.Focused = True Then Return True

        If bOcorrencias.Focused = True Then Return True

        If bGravar.Focused = True Then Return True

        If tPesquisa.Focused = True Then Return True

        If bPesquisar.Focused = True Then Return True

        If bCancelar.Focused = True Then Return True

        If cxPnLocalizar.Focused = True Then Return True

        Return False

    End Function

    Private Sub bCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCancelar.Click

        CancelarPesquisa()

    End Sub

    Private Sub bPesquisar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bPesquisar.Click

        Localizar()

    End Sub

    Private Sub CancelarPesquisa()

        IdPesq = 0

        PesqAtiva = False
        ConfigPorta = False

        lbl_Contador.Visible = False

        InputPanelTeclado.Enabled = False

        rdbMedidor.Checked = True
        rdbUc.Checked = False
        rdbRegistro.Checked = False

        lbl_Contador.Visible = False

        tPesquisa.Text = ""

        pnTeclado.Hide()
        pnOcorrencias.Hide()
        pnLocalizar.Hide()
        pnLeituras.Show()

        bOcorrencias.Enabled = True

        tUC.Focus()

    End Sub

    Private Sub rdbMedidor_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbMedidor.CheckedChanged

        If rdbMedidor.Checked = True Then

            IdPesq = 1
            tamCtlPesq = 12
            tPesquisa.Focus()

        End If

    End Sub

    Private Sub rdbUc_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbUc.CheckedChanged

        If rdbUc.Checked = True Then

            IdPesq = 2
            tamCtlPesq = 6
            tPesquisa.Focus()

        End If

    End Sub

    Private Sub rdbRegistro_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbRegistro.CheckedChanged

        If rdbRegistro.Checked = True Then

            IdPesq = 3

            If fts > 0 Then
                tamCtlPesq = fts.ToString.Length
            Else
                tamCtlPesq = numReg.ToString.Length
            End If

            tPesquisa.Focus()

        End If

    End Sub

    Private Sub tPesquisa_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tPesquisa.GotFocus

        InputPanelTeclado.Enabled = False
        pnTeclado.Show()
        lbl_Contador.Visible = True

    End Sub

    Private Sub rdbMedidor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbMedidor.Click

        If rdbMedidor.Checked = False Then

            rdbMedidor.Checked = True
            rdbUc.Checked = False
            rdbRegistro.Checked = False

        Else

            rdbUc.Checked = False
            rdbRegistro.Checked = False

        End If

    End Sub

    Private Sub rdbUc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbUc.Click

        If rdbUc.Checked = False Then

            rdbUc.Checked = True
            rdbMedidor.Checked = False
            rdbRegistro.Checked = False

        Else

            rdbMedidor.Checked = False
            rdbRegistro.Checked = False

        End If

    End Sub

    Private Sub rdbRegistro_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdbRegistro.Click

        If rdbRegistro.Checked = False Then

            rdbRegistro.Checked = True
            rdbMedidor.Checked = False
            rdbUc.Checked = False

        Else

            rdbMedidor.Checked = False
            rdbUc.Checked = False

        End If

    End Sub

    Private Sub tAcesso_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs)

        InputPanelTeclado.Enabled = True

    End Sub

    Private Sub AtualizaPorta(ByVal port As String)
        Dim sql As String = Nothing

        Try
            sql = "Update Controle Set IdPorta = '" & port & "'"

            conn.AbreConexao()

            conn.ExecutaComandoSQL(sql)

            conn.FechaConexao()

        Catch ex As Exception

            conn.FechaConexao()

        End Try

    End Sub

    Private Sub EFI_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Try

            updateDataHandler = New EventHandler(AddressOf UpdateData)

            'lbl_GPS.Text = ""

            'lbl_GPS.Width = Screen.PrimaryScreen.WorkingArea.Width

            'lbl_GPS.Height = Screen.PrimaryScreen.WorkingArea.Height

            AddHandler efiGPS.DeviceStateChanged, New DeviceStateChangedEventHandler(AddressOf gps_DeviceStateChanged)

            AddHandler efiGPS.LocationChanged, New LocationChangedEventHandler(AddressOf gps_LocationChanged)

        Catch ex As Exception

            'lbl_GPS.Text = ""

        End Try

    End Sub

    Private Sub gps_LocationChanged(ByVal sender As Object, ByVal args As LocationChangedEventArgs)

        Try

            position = args.Position

            ' call the UpdateData method via the updateDataHandler so that we
            ' update the UI on the UI thread
            Invoke(updateDataHandler)

        Catch ex As Exception

            position = Nothing

        End Try

    End Sub

    Private Sub gps_DeviceStateChanged(ByVal sender As Object, ByVal args As DeviceStateChangedEventArgs)

        Try

            device = args.DeviceState

            ' call the UpdateData method via the updateDataHandler so that we
            ' update the UI on the UI thread
            Invoke(updateDataHandler)

        Catch ex As Exception

            device = Nothing

        End Try

    End Sub

    Private Sub UpdateData(ByVal sender As Object, ByVal args As System.EventArgs)

        strLt = ""
        strLn = ""
        strDv = ""
        strDgLat = 11
        strDgLng = 37

        dtGPS = Now

        LatG = efiBs.DefaultLat
        LngG = efiBs.DefaultLong

        LatD = efiBs.DefaultLatitude.ToString
        LngD = efiBs.DefaultLongitude.ToString()

        Try

            If efiGPS.Opened = True Then

                If device IsNot Nothing Then
                    strDv = (device.FriendlyName.ToString & " " & _
                           device.ServiceState.ToString & ", ") & _
                           device.DeviceState & vbLf
                End If

                If position IsNot Nothing Then

                    If position.LatitudeValid Then

                        strLt = position.Latitude.ToString
                        strLn = position.Longitude.ToString
                        strDgLat = position.LatitudeInDegreesMinutesSeconds.Degrees
                        strDgLng = position.LongitudeInDegreesMinutesSeconds.Degrees
                        dtGPS = position.Time

                    End If

                End If

                statusGPS = strDv

                If strLt <> "" And strLn <> "" Then

                    CapturaCoordenaGPS()

                    LatG = Latitude.ToString.PadRight(13, "0").Replace(",", ".")
                    LngG = Longitude.ToString.PadRight(13, "0").Replace(",", ".")

                    txtLat.Text = "Lt:   " & LatG
                    txtLong.Text = "Lg: " & LngG

                    If newLatitude.ToString() = efiBs.DefaultLatitude.ToString() Or _
                       newLongitude.ToString() = efiBs.DefaultLongitude.ToString() Then

                        txtLat.ForeColor = Color.Red
                        txtLong.ForeColor = Color.Red

                    Else

                        txtLat.ForeColor = Color.Green
                        txtLong.ForeColor = Color.Green

                    End If

                    LatD = newLatitude.ToString()
                    LngD = newLongitude.ToString()

                Else

                    dtLeit = Format(Date.Now, "dd/MM/yy")
                    hrLeit = Format(Date.Now, "HH:mm")

                End If

            Else

                dtLeit = Format(Date.Now, "dd/MM/yy")
                hrLeit = Format(Date.Now, "HH:mm")

            End If

            GpsBase = True

        Catch ex As Exception

            Latitude = efiBs.DefaultLatitude.ToString
            Longitude = efiBs.DefaultLongitude.ToString()

            GpsBase = False
            txtLat.Text = "GPS sem sinal"
            txtLong.Text = ""
            txtLat.ForeColor = Color.Green
            txtLong.ForeColor = Color.Green

            dtLeit = Format(Date.Now, "dd/MM/yy")
            hrLeit = Format(Date.Now, "HH:mm")

        End Try

        latF = LatD.Replace(".", ",")
        lngF = LngD.Replace(".", ",")

        'Validando as Coordenadas Geográficas do GPS do Aparelho
        pLat = Math.Abs(CInt(efiMt.ValorDecimalTruncar(0, CDbl(latF))))
        pLng = Math.Abs(CInt(efiMt.ValorDecimalTruncar(0, CDbl(lngF))))

        If (pLat < 10 Or pLat > 11) Or (pLng < 37 Or pLng > 38) Then

            If dtLeit = "" Or dtLeit = Nothing Then

                dtLeit = Format(Date.Now, "dd/MM/yy")
                hrLeit = Format(Date.Now, "HH:mm")

            End If

            dtGPS = Format(Convert.ToDateTime(Date.Now), "dd/MM/yyyy HH:mm:ss")

            LatG = efiBs.DefaultLat
            LngG = efiBs.DefaultLong

            LatD = efiBs.DefaultLatitude.ToString
            LngD = efiBs.DefaultLongitude.ToString()

            utmX = efiBs.DefaultUtmX.ToString()
            utmY = efiBs.DefaultUtmY.ToString()


            GpsBase = False
            txtLat.Text = "Lendo GPS"
            txtLong.Text = ""
            txtLat.ForeColor = Color.Green
            txtLong.ForeColor = Color.Green

        End If

        If LatD.ToString.Length > 15 Then
            LatD = LatD.ToString.Replace(".", ",").Substring(0, 15)
        Else
            LatD = LatD.ToString.Replace(".", ",")
        End If

        If LngD.ToString.Length > 15 Then
            LngD = LngD.ToString.Replace(".", ",").Substring(0, 15)
        Else
            LngD = LngD.ToString.Replace(".", ",")
        End If

    End Sub

    Private Sub CapturaCoordenaGPS()

        Try

            Dim stGPGLL As Boolean = False
            Dim stGPZDA As Boolean = False

            dtLeit = Format(dtGPS, "dd/MM/yyyy")
            hrLeit = Format(dtGPS, "HH:mm:ss")

            Select Case hrLeit.Substring(0, 2)
                Case Is = "00"
                    hrLeit = "21" & hrLeit.Substring(2, 6)
                Case Is = "01"
                    hrLeit = "22" & hrLeit.Substring(2, 6)
                Case Is = "02"
                    hrLeit = "23" & hrLeit.Substring(2, 6)
                Case Else
                    hrLeit = (hrLeit.Substring(0, 2) - 3).ToString.PadLeft(2, "0") & _
                             hrLeit.Substring(2, 6)
            End Select

            dtGPS = Convert.ToDateTime(dtLeit & " " & hrLeit)

            stGPZDA = True

            'Latitude 
            newLatitude = strLt.ToString.Replace(",", ".")
            Dim dLat As UInteger = strDgLat
            Dim tLat As Double = efiMt.ValorDecimalArred(8, CObj(strLt) * -1)
            Dim rLat As Double = efiMt.ValorDecimalTruncar(8, tLat - dLat)
            Dim nLat As Double = efiMt.ValorDecimalArred(5, rLat * 60)
            Latitude = "S" & dLat.ToString & "º " & nLat.ToString.Replace(",", ".")

            'Longitude
            newLongitude = strLn.ToString.Replace(",", ".")
            Dim dLng As UInteger = strDgLng
            Dim tLng As Double = efiMt.ValorDecimalArred(8, CObj(strLn) * -1)
            Dim rLng As Double = efiMt.ValorDecimalTruncar(8, tLng - dLng)
            Dim nLng As Double = efiMt.ValorDecimalArred(5, rLng * 60)
            Longitude = "W" & dLng.ToString & "º " & nLng.ToString.Replace(",", ".")

            stGPGLL = True

            If stGPGLL = True And stGPZDA = True Then

                'Atualizando Tabela
                efiBs.ls = New EfiBase.Lista
                efiBs.lst = New List(Of EfiBase.Lista)()
                efiBs.ls.dtSeq = dtGPS
                efiBs.ls.Latitude = Latitude.ToString()
                efiBs.ls.Longitude = Longitude.ToString()
                efiBs.lst.Add(efiBs.ls)

                efiBs.myLatitude = newLatitude
                efiBs.myLongitude = newLongitude

            End If

            Latitude = efiBs.ls.Latitude.ToString()
            Longitude = efiBs.ls.Longitude.ToString()

            newLatitude = efiBs.myLatitude
            newLongitude = efiBs.myLongitude

            dtLeit = Format(dtGPS, "dd/MM/yy")
            hrLeit = Format(dtGPS, "HH:mm")

        Catch

            Latitude = efiBs.ls.Latitude.ToString()
            Longitude = efiBs.ls.Longitude.ToString()

            newLatitude = efiBs.myLatitude
            newLongitude = efiBs.myLongitude

            dtGPS = Format(Convert.ToDateTime(Date.Now), "dd/MM/yyyy HH:mm:ss")

            dtLeit = Format(Date.Now, "dd/MM/yy")
            hrLeit = Format(Date.Now, "HH:mm")

        End Try

    End Sub

    Private Sub LigarGPS()

        If efiGPS.Opened = False Then

            efiGPS.Open()

        End If

    End Sub

    Private Sub DesligarGPS()

        If efiGPS.Opened = True Then

            efiGPS.Close()

        End If

    End Sub

    Private Sub MenuTransferencia_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuTransferencia.Click

        Dim sql As String = Nothing
        Dim dr As SqlCeDataReader = Nothing
        Dim drL As SqlCeDataReader = Nothing
        Dim l As New List(Of String)

        pnOcorrencias.Hide()
        pnLocalizar.Hide()
        pnTeclado.Hide()
        pnLeituras.Hide()
        pnLogin.Show()

        Cursor.Current = Cursors.WaitCursor

        HabilitarControles_PnLogin()

        conn.AbreConexao()

        l.Clear()

        'Interação C#:
        'Verifica se no SQL Server o status:
        Dim obj As New EFITransmissao.Entidade.Roteiro
        Dim aux = False

        sql = "Select Remessa, MesFat, Matricula From Controle"
        dr = conn.PreencheDataReader(sql)

        If dr.Read() = True Then
            obj.Remessa = dr.GetValue(0).ToString()
            obj.MesFat = dr.GetValue(1).ToString().Substring(3, 2) + dr.GetValue(1).ToString().Substring(6, 4)
            obj.Matricula = dr.GetValue(2).ToString()
            aux = True
        End If

        If aux = True Then

            If EFITransmissao.Interface.InterTransmissao.StatusRoteiroDisponivel(obj) = True Then

                sql = "Update Controle Set RoteiroRecebido = 0"
                conn.ExecutaComandoSQL(sql)

                MenuColetar.Enabled = False

            Else
                If EFITransmissao.Interface.InterTransmissao.StatusLeituraDisponivel(obj) = True Then

                    sql = "Update Controle Set LeiturasEnviadas = 0"
                    conn.ExecutaComandoSQL(sql)

                    MenuColetar.Enabled = True

                End If
            End If

        End If

        sql = "Select RoteiroRecebido, LeiturasEnviadas From Controle"
        dr = conn.PreencheDataReader(sql)

        If dr.Read() = True Then

            If dr.GetValue(0) = True And dr.GetValue(1) = False Then

                sql = "Select Matricula, Leiturista From Controle"
                drL = conn.PreencheDataReader(sql)

                If drL.Read() = True Then

                    'l.Add(drL.GetValue(0).ToString())
                    l.Add(EFITransmissao.Controle.CtlLeiturista.ObterNomeLeiturista(CInt(drL.GetValue(0).ToString())))
                    cbLeituristas_pnLogin.DataSource = l

                End If

                drL.Close()
                'Envio de Leituras
                cbLeituristas_pnLogin.Refresh()
                cbLeituristas_pnLogin.Focus()
                cbLeituristas_pnLogin.Enabled = False
                txtMatricula_pnLogin.Focus()
                txtMatricula_pnLogin.Focus()

            Else

                If System.IO.Directory.Exists("\\Alfa\Municipios\Estancia\ColetadeLeitura") = True Then
                    'Atualizar Banco Sdf
                    EFITransmissao.Controle.CtlLeiturista.InserirLeituristaCE()
                End If

                'Receber Roteiro:
                'Carregar Lista            
                cbLeituristas_pnLogin.DataSource = Controle.CtlLeiturista.ObterLeituristasCE()
                cbLeituristas_pnLogin.Refresh()
                cbLeituristas_pnLogin.Focus()
                cbLeituristas_pnLogin.Enabled = True

            End If

        Else

            If System.IO.Directory.Exists("\\Alfa\Municipios\Estancia\ColetadeLeitura") = True Then
                'Atualizar Banco Sdf
                EFITransmissao.Controle.CtlLeiturista.InserirLeituristaCE()
            End If

            'Carregar Lista            
            cbLeituristas_pnLogin.DataSource = Controle.CtlLeiturista.ObterLeituristasCE()
            cbLeituristas_pnLogin.Refresh()
            cbLeituristas_pnLogin.Focus()
            cbLeituristas_pnLogin.Enabled = True

        End If

        dr.Close()
        conn.FechaConexao()

        Cursor.Current = Cursors.Default

    End Sub

    Private Sub lkFechar_PnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkFechar_PnLogin.Click

        pnLogin.Hide()

    End Sub

    Private Sub btOk_pnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btOk_pnLogin.Click

        InputPanelTeclado.Enabled = False

        'Valida
        If cbLeituristas_pnLogin.Text = String.Empty Or txtMatricula_pnLogin.Text = String.Empty Then
            Exit Sub
        End If

        If Not IsNumeric(txtMatricula_pnLogin.Text) Then

            txtMatricula_pnLogin.Text = Nothing
            MessageBox.Show("Apenas número para esse campo!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
            txtMatricula_pnLogin.Focus()
            Exit Sub

        Else
            If CInt(txtMatricula_pnLogin.Text) <> EFITransmissao.Controle.CtlLeiturista.ValidaMatricula(cbLeituristas_pnLogin.Text) Then
                MessageBox.Show("Matrícula inválida!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                Exit Sub
            End If
        End If

        DesabilitarControles_PnLogin()

        Try

            Dim rt As New EFITransmissao.Entidade.Roteiro
            rt = EFITransmissao.Controle.CtlLeiturista.ObterLeituraDisponivel(txtMatricula_pnLogin.Text)

            'Habilita Controles para recepção/transmissão:
            'Verifica se ainda há leitura a ser descarregada.
            If EFITransmissao.Controle.CtlLeiturista.ObterStatusLeituraDisponivel(rt) Then
                btEnviarLeituras_pnLogin.Visible = True
                btReceberRoteiro_pnLogin.Visible = False
            Else
                btReceberRoteiro_pnLogin.Visible = True
                btEnviarLeituras_pnLogin.Visible = False
            End If

        Catch ex As Exception
            DesabilitarControles_PnLogin()
            pnLogin.Hide()
            MessageBox.Show("Não foi encontrado o sinal da rede Wi-fi.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
        End Try


    End Sub

    Private Sub HabilitarControles_PnLogin()

        lbLeiturista_pnLogin.Visible = True
        lbMatricula_pnLogin.Visible = True
        cbLeituristas_pnLogin.Visible = True
        txtMatricula_pnLogin.Visible = True
        btCancel_pnLogin.Visible = True
        btOk_pnLogin.Visible = True

        cbLeituristas_pnLogin.Text = String.Empty
        txtMatricula_pnLogin.Text = String.Empty
        cbLeituristas_pnLogin.Focus()

        btEnviarLeituras_pnLogin.Visible = False
        btReceberRoteiro_pnLogin.Visible = False

    End Sub

    Private Sub DesabilitarControles_PnLogin()

        lbLeiturista_pnLogin.Visible = False
        lbMatricula_pnLogin.Visible = False
        cbLeituristas_pnLogin.Visible = False
        txtMatricula_pnLogin.Visible = False
        btCancel_pnLogin.Visible = False
        btOk_pnLogin.Visible = False

    End Sub

    Private Sub btCancel_pnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btCancel_pnLogin.Click

        InputPanelTeclado.Enabled = False
        pnLogin.Hide()

    End Sub

    Private Sub btReceberRoteiro_pnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btReceberRoteiro_pnLogin.Click

        Try

            If EFITransmissao.Interface.InterTransmissao.StatusRoteiroDisponivel(txtMatricula_pnLogin.Text) = True Then

                Cursor.Current = Cursors.WaitCursor

                EFITransmissao.Interface.InterTransmissao.LimparRecebidosLocal()

                If EFITransmissao.Interface.InterTransmissao.DeletePDAFotosColeta(cbLeituristas_pnLogin.Text) = False Then
                    MessageBox.Show("Fotos referentes as UC's não podem ser deletadas.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                    MessageBox.Show("Processo de Recebimento CANCELADO.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)
                    Exit Sub
                End If

                If EFITransmissao.Interface.InterTransmissao.DeletePDAFotosExterna(cbLeituristas_pnLogin.Text) = False Then
                    MessageBox.Show("Fotos Externas não podem ser enviadas.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                    MessageBox.Show("Processo de Recebimento CANCELADO.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)
                    Exit Sub
                End If

                'Receber Novo Roteiro do Servidor:
                'Obter do Servidor os arquivos txt para o Disp. Móvel.
                If EFITransmissao.Interface.InterTransmissao.ObterArquivosRoteiro_Servidor(cbLeituristas_pnLogin.Text) = True Then

                    'Lendo arquivo (Leitura e Controle) e gravando no DB.
                    LerNovoArquivoTxt()

                Else
                    MessageBox.Show("Arquivos de carga do roteiro não encontrado.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)
                End If
            Else
                MessageBox.Show("O Roteiro ainda não está disponível.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
            End If

            Cursor.Current = Cursors.Default

        Catch ex As Exception

            Cursor.Current = Cursors.Default
            MessageBox.Show("Erro ao receber o novo roteiro. Erro: " + ex.Message, "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)

        End Try

    End Sub

    Private Sub btEnviarLeituras_pnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btEnviarLeituras_pnLogin.Click
        Dim sql As String = Nothing

        Try

            If GerarArquivoLeiturasParaEnvio() = True Then

                Cursor.Current = Cursors.WaitCursor
                If EFITransmissao.Interface.InterTransmissao.EnviarArquivosLeituras_ServidorBackup(cbLeituristas_pnLogin.Text) = False Then

                    MessageBox.Show("Arquivo de leitura não foi gerado para ser enviado.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)

                Else
                    If EFITransmissao.Interface.InterTransmissao.EnviarArquivosLeituras_Servidor(cbLeituristas_pnLogin.Text) = False Then

                        MessageBox.Show("Arquivo de leitura não foi gerado para ser enviado.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)

                    Else

                        If EFITransmissao.Interface.InterTransmissao.TransferenciaFotosColeta(cbLeituristas_pnLogin.Text) = False Then
                            MessageBox.Show("Fotos referentes as UC's não podem ser enviadas.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                            MessageBox.Show("Processo de envio das Leituras NÃO pode ser realizado.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)

                            Cursor.Current = Cursors.Default
                            'Desfaz atualização.
                            conn.AbreConexao()

                            sql = "Update Controle Set LeiturasEnviadas = 0"
                            conn.ExecutaComandoSQL(sql)

                            conn.FechaConexao()

                            Exit Sub
                        End If

                        If EFITransmissao.Interface.InterTransmissao.TransferenciaFotosExterna(cbLeituristas_pnLogin.Text) = False Then
                            MessageBox.Show("Fotos Externas não podem ser enviadas.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
                            MessageBox.Show("Processo de envio das Leituras NÃO pode ser realizado.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)

                            Cursor.Current = Cursors.Default
                            'Desfaz atualização.
                            conn.AbreConexao()

                            sql = "Update Controle Set LeiturasEnviadas = 0"
                            conn.ExecutaComandoSQL(sql)

                            conn.FechaConexao()

                            Exit Sub
                        End If

                        'Atualizar Flag de Concluído na tabela de controle de Leitura.
                        Dim rt As New EFITransmissao.Entidade.Roteiro
                        rt = Controle.CtlLeiturista.ObterLeituraDisponivel(txtMatricula_pnLogin.Text)

                        EFITransmissao.Controle.CtlLeiturista.AtualizandoControleLeituraSQL(rt)

                        pnLogin.Hide()

                        MessageBox.Show("Arquivo de leitura enviado com sucesso.", "Informação!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1)

                        'Application.Exit()

                    End If

                End If

            End If

            Cursor.Current = Cursors.Default

        Catch ex As Exception

            'Desfaz atualização.
            conn.AbreConexao()

            sql = "Update Controle Set LeiturasEnviadas = 0"
            conn.ExecutaComandoSQL(sql)

            conn.FechaConexao()

            Cursor.Current = Cursors.Default

            MessageBox.Show("Erro ao enviar as leituras.", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)

        End Try

    End Sub

    Private Sub txtMatricula_pnLogin_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMatricula_pnLogin.GotFocus
        InputPanelTeclado.Enabled = False

        pnOcorrencias.Hide()

        If PesqAtiva = False Then

            InputPanelTeclado.Enabled = True

        Else

            InputPanelTeclado.Enabled = False
            btCancel_pnLogin.Focus()

        End If
    End Sub

    Private Sub MenuAdm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuAdm.Click

        Dim frm As New EFITransmissao.FrmADM
        frm.Show()

    End Sub

    Private Sub EFI_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If (e.KeyCode = System.Windows.Forms.Keys.Up) Then
            'Up
        End If
        If (e.KeyCode = System.Windows.Forms.Keys.Down) Then
            'Down
        End If
        If (e.KeyCode = System.Windows.Forms.Keys.Left) Then
            'Left
        End If
        If (e.KeyCode = System.Windows.Forms.Keys.Right) Then
            'Right
        End If
        If (e.KeyCode = System.Windows.Forms.Keys.Enter) Then
            'Enter
        End If

    End Sub

    Private Sub MenuCamera_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuCamera.Click

        Dim frm As New EFITransmissao.FrmCamera
        frm.Show()

        'AnoMesDia_HHmmss
        FrmCamera.ObterNomenclatura(String.Empty)

    End Sub
End Class